package com.hycloud.cloudstack.common;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

public class WebUtils {

	 public static Map<String,String> getParameterAsMap( HttpServletRequest request ) {
		Map<String,String[]> params = request.getParameterMap();
		Map<String,String> newParams = new HashMap<>();
		
		for (Map.Entry<String, String[]> entry: params.entrySet()) {
			String key = entry.getKey();
			String[] value = entry.getValue();
			if ( value.length ==1  && StringUtils.isNotBlank(value[0])) {
				newParams.put(key, value[0]);
			} else if ( value.length > 1) {
				for ( int i = 0; i < value.length; i++) {
					newParams.put(key+"[" + i + "]", value[i]);
				}
			}
		}
		
		return newParams;
	}
	 
	 public static void writeJsonResponse( HttpServletResponse response, String res , int statusCode) {
			try {
				response.setContentType("application/json;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");
				response.setHeader("Charset", "UTF-8");
				response.setHeader("Cache-Control", "no-cache");
				response.setStatus(statusCode);
				response.getWriter().print(res);
			} catch (IOException e) {
			}
		}
}
